<template>
  <el-radio-group
    v-model="internalRole"
    :button="button"
    :student="student"
    :teacher="teacher"
    :admin="admin"
    @change="handleRoleChange"
  >
    <div v-if="button">
      <el-radio-button v-if="student" :label="ROLE.STUDENT">学生</el-radio-button>
      <el-radio-button v-if="teacher" :label="ROLE.TEACHER">教师</el-radio-button>
      <el-radio-button v-if="admin" :label="ROLE.ADMIN">教务</el-radio-button>
    </div>
    <div v-else>
      <el-radio v-if="student" :label="ROLE.STUDENT">学生</el-radio>
      <el-radio v-if="teacher" :label="ROLE.TEACHER">教师</el-radio>
      <el-radio v-if="admin" :label="ROLE.ADMIN">教务</el-radio>
    </div>
  </el-radio-group>
</template>

<script>
import { ROLE } from '@/constant/user'

export default {
  name: 'RoleRadio',
  props: {
    value: {
      type: String,
      required: true
    },
    button: {
      type: Boolean,
      default: false
    },
    student: {
      type: Boolean,
      default: false
    },
    teacher: {
      type: Boolean,
      default: false
    },
    admin: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 内部使用的变量 与外部传入的value保持同步
      internalRole: this.value,
      ROLE: ROLE
    }
  },
  watch: {
    internalRole(newVal) {
      // 监听内部变量变化 并同步到外部value
      this.$emit('input', newVal)
    },
    value(newVal) {
      // 监听外部value变化 并同步到内部变量
      this.internalRole = newVal
    }
  },
  methods: {
    /**
     * 角色变化
     * @param value 变化的值
     */
    handleRoleChange(value) {
      // 更新内部变量以确保与父组件的v-model保持同步
      this.internalRole = value
      // 发送自定义事件 通知父组件性别已改变
      this.$emit('role-change', value)
    }
  }
}
</script>
